import React, {Component} from 'react';
import {
	add,
	reduce,
	addAsync,
} from '../../redux/actions/count';

// 引入connect用于连接ui组件与redux
import {connect} from 'react-redux';

class Count extends Component {
	// componentDidMount() {
	// 	// 当redux的store改变时触发此函数,达到舒心reder目的
	// 	store.subscribe(() => this.setState({}));
	// }

	// 普通加
	add = () => {
		const {value} = this.selectNumber;
		this.props.jia(value * 1);
	};

	// 普通减
	reduce = () => {
		const {value} = this.selectNumber;
		this.props.jian(value * 1);
	};

	// 奇数添加
	oddNumberAdd = () => {
		const sum = this.props.count;
		const {value} = this.selectNumber;
		if (sum % 2 !== 0) {
			this.props.jia(value * 1);
		}
	};

	// 异步添加
	asynAdd = () => {
		const {value} = this.selectNumber;
		this.props.yibujia(value * 1, 500);
	};

	render() {
		return (
			<div>
				<h1>我是Count组件</h1>
				<h4>
					<span>当前总数:{this.props.count}</span>
					<br />
					<span>下方组件总人数:{this.props.person.length}</span>
				</h4>
				<div>
					<select ref={c => (this.selectNumber = c)}>
						<option value="1">1</option>
						<option value="2">2</option>
						<option value="3">3</option>
					</select>
					<button onClick={this.add}>+</button>
					<button onClick={this.reduce}>-</button>
					<button onClick={this.oddNumberAdd}>奇数添加</button>
					<button onClick={this.asynAdd}>异步添加</button>
				</div>
			</div>
		);
	}
}

// 使用connect()()创建并暴露一个Count的容器组件
export default connect(
	state => {
		return {count: state.count, person: state.person};
	},
	{jia: add, jian: reduce, yibujia: addAsync} // 究极简写
)(Count);
